<?php
$password = $_POST['password'] ?? 'null';
if ($password === 'null') {
    echo "<script>alert('Password is empty');location='gapwp.php';</script>";
    exit;
}
session_start();
require($_SERVER['DOCUMENT_ROOT'] . '/cofd/common.php');
$md5pass = md5($password);
$sql_select = "SELECT username FROM users LIMIT 1";
$stmt_select = $conn->prepare($sql_select);
if (!$stmt_select) {
    echo "<script>alert('Database error: " . htmlspecialchars($conn->error) . "');location='gapwp.php';</script>";
    exit;
}

$stmt_select->execute();
$result = $stmt_select->get_result();
if ($result->num_rows > 0) {
    $row = $result->fetch_assoc();
    $adminaccount = $row['username'];
} else {
    echo "<script>alert('No user found');location='gapwp.php';</script>";
    exit;
}
$sql_update = "UPDATE users SET `password` = ? WHERE username = ?";
$stmt_update = $conn->prepare($sql_update);
if (!$stmt_update) {
    echo "<script>alert('Database error: " . htmlspecialchars($conn->error) . "');location='gapwp.php';</script>";
    exit;
}

$stmt_update->bind_param('ss', $md5pass, $adminaccount);
if (!$stmt_update->execute()) {
    echo "<script>alert('Failed to update password: " . htmlspecialchars($stmt_update->error) . "');location='gapwp.php';</script>";
    exit;
}
session_regenerate_id(true);
session_destroy();
session_write_close();
echo "<script>alert('Password updated successfully');location='login.php';</script>";
?>